package com.boot.notice;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.boot.utils.OkHttpUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class AllNotice {

    /**
     * 调用接口 post
     * @param apiPath
     */
    public String doGetPost(String apiPath,String type,Map<String,Object> paramMap){
        OutputStreamWriter out = null;
        InputStream is = null;
        String result = null;
        try{
            URL url = new URL(apiPath);// 创建连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod(type) ; // 设置请求方式
            connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
            connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
            connection.connect();
            if(type.equals("POST")){
                out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码
                out.append(JSON.toJSONString(paramMap));
                out.flush();
                out.close();
            }
            // 读取响应
            is = connection.getInputStream();
            int length = (int) connection.getContentLength();// 获取长度
            if (length != -1) {
                byte[] data = new byte[length];
                byte[] temp = new byte[512];
                int readLen = 0;
                int destPos = 0;
                while ((readLen = is.read(temp)) > 0) {
                    System.arraycopy(temp, 0, data, destPos, readLen);

                    destPos += readLen;
                }
                result = new String(data, "UTF-8"); // utf-8编码

            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return  result;
    }

    /**
     * 获取公众号的授权token
     * @return
     */
    public String getAccessToken(){
        String grant_type = "client_credential";
        String appid = "wxc786313130576c14";
        String secret = "1e0a8cab5a4088cd5adbdc918a0d54e7";
        String getTokenApi = "https://api.weixin.qq.com/cgi-bin/token?grant_type="+grant_type+"&appid="+appid+"&secret="+secret;
        String tokenJsonStr =  doGetPost(getTokenApi,"GET",null);
        JSONObject tokenJson = JSONObject.parseObject(tokenJsonStr);
        System.out.println(tokenJson);
        String token = tokenJson.get("access_token").toString();
        System.err.println("获取公众号的授权token：" + token);
        return token;
    }

    public static void main(String[] args) throws Exception {
        AllNotice an = new AllNotice();
        an.SendWeChatMsg();
    }

    /**
     * 发送通知
     */
    public void SendWeChatMsg() throws Exception {
        String token = getAccessToken();
        //Jedis jedis=new Jedis("localhost");
        // 获取密令（access_token）
        //String token = jedis.get("access_token");//jsone.get("access_token").toString();
        //System.err.println("获得的access_token值-----" + token);

        //接口地址
        String sendMsgApi = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+token;
        //openId
        //String toUser = "obkpnuOF0HZ1m7uByT_0_Ce36bTc";
        //消息模板ID
        //String template_id = "S7z2oHNjxLYxcWEKcPRoWb93pziZdgQFYLoJNmL0OYs";
        String toUrl = "http://weixin.qq.com/download";
        //整体参数map
        Map<String, Object> paramMap = new HashMap<>();
        //点击消息跳转相关参数map
        Map<String, String> miniprogramMap = new HashMap<>();
        //消息主题显示相关map
        Map<String, Object> dataMap = new HashMap<>();

        miniprogramMap.put("appid","wxf5780a1089690ac9");
        miniprogramMap.put("pagepath","/pages/home/home");

        dataMap.put("first", new contentDTO("[BeeWon] 欢迎您的再次到来!!!", "#111111"));
        dataMap.put("keyword1", new contentDTO("BEE20210819154216269", "#173177"));
        dataMap.put("keyword2", new contentDTO("支付成功", "#173177"));
        dataMap.put("keyword3", new contentDTO("2021-09-08 10:09:09", "#173177"));
        dataMap.put("keyword4", new contentDTO("蜜蜂嗡嗡商城", "#173177"));
        dataMap.put("keyword5", new contentDTO("36.9元", "#173177"));
        dataMap.put("remark", new contentDTO("", ""));

        paramMap.put("touser", "o2Q8_54DJmR-lzyE6DzRNTEfTk20");
        paramMap.put("template_id", "oj9syg3JSH5jucSyp6FKASVoett2B2dv-cdfphXSPYY");
        paramMap.put("url", "");
        paramMap.put("miniprogram", miniprogramMap);
        paramMap.put("data", dataMap);
        System.err.println(doGetPost(sendMsgApi,"POST",paramMap));

    }

}
